package com.example.admin.goodnews.activity;

import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.admin.goodnews.R;
import com.example.admin.goodnews.adapter.BaseFragmentAdapter;
import com.example.admin.goodnews.adapter.FragmentAdapter;
import com.example.admin.goodnews.adapter.ListViewAdapter;
import com.example.admin.goodnews.database.MyDBHelper;
import com.example.admin.goodnews.database.MyDBManager;
import com.example.admin.goodnews.entity.GoodNewsClassEntity;
import com.example.admin.goodnews.entity.NewsClassEntity;
import com.example.admin.goodnews.event.DBChangeEvent;
import com.example.admin.goodnews.fragment.BaseFragment;
import com.example.admin.goodnews.fragment.DianYingPaiHang.DianYingPaiHangFragment;
import com.example.admin.goodnews.fragment.MeiTuDaQuan.MeiTuDaQuanFragment;
import com.example.admin.goodnews.fragment.QingSongYiXia.QingSongYiXiaFragment;
import com.example.admin.goodnews.fragment.ShengHuoChangYong.ShengHuoChangYongFragment;
import com.example.admin.goodnews.fragment.DiQuXinWen.DiQuXinWenFragment;
import com.example.admin.goodnews.fragment.ReSouXinWen.ReSouXinWenFragment;
import com.example.admin.goodnews.fragment.WuLiaoDianWo.TuLingJiQiRenFragment;
import com.example.admin.goodnews.fragment.ZaiXianYinYue.ZaiXianYinYueFragment;
import com.example.admin.goodnews.utils.HttpUtils;
import com.example.admin.goodnews.utils.NetWorkDataUrl;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;


/*
 *  主页面
 */
public class MainActivity extends AppCompatActivity {
    private Toolbar toolbar;
    // private CoordinatorLayout coordinatorlayout;
    private DrawerLayout drawerlayout_main;
    private ListView listview_slidemenu;// 侧滑菜单里的ListView
    // private LinearLayout login;// 点击后跳转到登陆页面
    private CircleImageView cir_header_sliedemenu;// 用户的头像
    private TextView tv_login;//  登录
    private TextView tv_logout;//  登录后变成退出
    private ImageView iv_addchannel;// 添加频道按钮
    private Toolbar toolbar_title;// 标题栏
    private ActionBarDrawerToggle drawerToggle;// 侧滑状态监听管理器
    private RelativeLayout relativelayout_main;// 主页加载Fragment

    private LinearLayout slide_part;// 侧滑的部分
    private ListViewAdapter listViewAdapter;// 侧滑菜单中ListView的适配器
    private FragmentManager manager;//创建Fragment管理者
    private FragmentTransaction transaction;//创建事务
    private GoodNewsClassEntity goodNewsClassEntity;// 新闻分类的实体类
    private List<String> lists = new ArrayList<>();// 存放侧滑菜单数据

    private List<String> defaultlists = new ArrayList<>();// 存放部分新闻分类的列表
    private List<String> tablists = new ArrayList<>();
    private List<BaseFragment> defaultfragmentlists = new ArrayList<>();// 存放部分新闻分类的列表
    private BaseFragmentAdapter baseFragmentAdapter;

    private ViewPager viewpager_main;// 装载Fragment的容器
    private FragmentAdapter fragmentAdapter;// ViewPager适配器
    private NewsClassEntity newsClassEntity;// 全部新闻分类实体类
    private TabLayout tablayout_main;// 标题栏
    private ImageView iv_morechannel;// 频道管理按钮

    private MyDBHelper dbhelper = new MyDBHelper(MainActivity.this);
    private SQLiteDatabase db;
    private MyDBManager dbmanager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 注册EventBus
        EventBus.getDefault().register(MainActivity.this);
        initView();
        initEvent();
        initData();
        bindData();
        settitles();
    }

    private void initView() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        // coordinatorlayout = (CoordinatorLayout) findViewById(R.id.coordinatorlayout);
        listview_slidemenu = (ListView) findViewById(R.id.listview_slidemenu);// 侧滑菜单里的ListView
        // login = (LinearLayout) findViewById(R.id.login);// 点击后跳转到登陆页面

        cir_header_sliedemenu = (CircleImageView) findViewById(R.id.cir_header_sliedemenu);// 用户的头像，点击后跳转到用户个人页面
        tv_login = (TextView) findViewById(R.id.tv_login);// 登录
        tv_logout = (TextView) findViewById(R.id.tv_logout);//  登录后变成退出
        drawerlayout_main = (DrawerLayout) findViewById(R.id.drawerlayout_main);
        relativelayout_main = (RelativeLayout) findViewById(R.id.relativelayout_main);// 主页加载Fragment
        //linearlayout_main = (LinearLayout) findViewById(R.id.linearlayout_main);
        slide_part = (LinearLayout) findViewById(R.id.slide_part);// 侧滑的部分

        viewpager_main = (ViewPager) findViewById(R.id.viewpager_main);
        tablayout_main = (TabLayout) findViewById(R.id.tablayout_main);
        iv_morechannel = (ImageView) findViewById(R.id.iv_morechannel);
        // 点击跳转到频道管理页面
        iv_morechannel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, ChannelManageActivity.class);
                startActivity(intent);
            }
        });
    }

    // 给GridView标签绑定新闻分类数据
    private void bindData() {
        try {
            HttpUtils.doPostAsyn(NetWorkDataUrl.ALLWEBURL_url, NetWorkDataUrl.ALLWEBURL_PARAM, new HttpUtils.CallBack() {
                @Override
                public void onRequestComplete(String result) {
                    Gson gson = new Gson();
                    newsClassEntity = gson.fromJson(result, NewsClassEntity.class);
                    if (newsClassEntity.getShowapi_res_body().getChannelList().size() > 0) {
                        handler.sendEmptyMessage(2);
                    } else {
                        handler.sendEmptyMessage(0);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 设置已选频道并显示
    private void settitles() {
//        defaultlists.add("国内焦点");
//        defaultlists.add("国际焦点");
//        defaultlists.add("军事焦点");
//        defaultlists.add("财经焦点");
//        defaultlists.add("体育焦点");
//        defaultlists.add("娱乐焦点");
//        defaultlists.add("教育焦点");
//        defaultlists.add("科技焦点");

        db = dbhelper.getWritableDatabase();
        dbmanager = new MyDBManager(dbhelper, db);
        defaultlists = dbmanager.querydata();

//        for (int i = 0; i < defaultlists.size(); i++) {
//            dbmanager.insertdata(defaultlists.get(i));
//        }

        // 设置GridView单行显示
//        int size = defaultlists.size();
//        int length = 100;
//        DisplayMetrics dm = new DisplayMetrics();
//        getWindowManager().getDefaultDisplay().getMetrics(dm);
//        float density = dm.density;
//        int gridviewWidth = (int) (size * (length + 4) * density);
//        int itemWidth = (int) (length * density);
//        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
//                gridviewWidth, LinearLayout.LayoutParams.MATCH_PARENT);
//        gridview_main.setLayoutParams(params); // 设置GirdView布局参数,横向布局的关键
//        gridview_main.setColumnWidth(itemWidth); // 设置列表项宽
//        gridview_main.setHorizontalSpacing(5); // 设置列表项水平间距
//        gridview_main.setStretchMode(GridView.NO_STRETCH);
//        gridview_main.setNumColumns(size); // 设置列数量=列表集合数
//        gridViewAdapter = new GridViewAdapter(MainActivity.this, defaultlists);
//        gridview_main.setAdapter(gridViewAdapter);


        List<BaseFragment> list = new ArrayList<>();
        for (int i = 0; i < defaultlists.size(); i++) {
            String channelName = defaultlists.get(i);
            BaseFragment baseFragment = BaseFragment.newInstance(channelName);
            list.add(baseFragment);
        }

        baseFragmentAdapter = new BaseFragmentAdapter(getSupportFragmentManager(), defaultlists, list);
        viewpager_main.setAdapter(baseFragmentAdapter);
        // 设置标题TabLayout
        tablayout_main.setupWithViewPager(viewpager_main);
        viewpager_main.setCurrentItem(0);
    }

    // 侧滑菜单内容
    private void initData() {
        lists.add("新闻资讯");
        lists.add("热搜新闻");
        lists.add("地区新闻");
        lists.add("电影排行");
        lists.add("轻松一下");
        lists.add("在线音乐");
        lists.add("美图大全");
        lists.add("无聊点我");
        lists.add("生活常用");
        if (lists.size() > 0) {
            handler.sendEmptyMessage(1);
        } else {
            handler.sendEmptyMessage(0);
        }
    }

    private void initEvent() {
        toolbar.setTitle("好新闻");
//        toolbar.setSubtitle("发现好新闻");
        toolbar.setTitleTextColor(Color.WHITE);
        toolbar.setSubtitleTextColor(Color.WHITE);
        setSupportActionBar(toolbar);
        drawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawerlayout_main, R.string.open, R.string.close) {
            @Override
            public void onDrawerOpened(View drawerView) {
                invalidateOptionsMenu();        //在onDrawerOpened中的作用是打开侧滑菜单并让其可见
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                invalidateOptionsMenu();        //在onDrawerOpened中的作用是关闭侧滑菜单并让其不可见
            }
        };
        drawerToggle.syncState();
        drawerlayout_main.setDrawerListener(drawerToggle);
        ActionBar ab = getSupportActionBar();
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setHomeButtonEnabled(true);
        // 点击登录
        tv_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent_tologin = new Intent(MainActivity.this, LoginActivity.class);
                startActivity(intent_tologin);
                drawerlayout_main.closeDrawer(slide_part);
            }
        });
        //  点击头像跳转到用户个人页面
        cir_header_sliedemenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent_userinfo = new Intent(MainActivity.this, UserInfoActivity.class);
                startActivity(intent_userinfo);
                drawerlayout_main.closeDrawer(slide_part);
            }
        });

        // 侧滑菜单栏点击事件
        listview_slidemenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                manager = getSupportFragmentManager();
                transaction = manager.beginTransaction();
                switch (position) {
                    // 新闻资讯
                    case 0:
                        Intent intent = new Intent(MainActivity.this, MainActivity.class);
                        startActivity(intent);
                        break;
                    // 热搜新闻
                    case 1:
                        transaction.replace(R.id.relativelayout_main, new ReSouXinWenFragment());
                        break;
                    // 地区新闻
                    case 2:
                        transaction.replace(R.id.relativelayout_main, new DiQuXinWenFragment());
                        break;
                    // 电影排行
                    case 3:
                        transaction.replace(R.id.relativelayout_main, new DianYingPaiHangFragment());
                        break;
                    // 轻松一下
                    case 4:
                        transaction.replace(R.id.relativelayout_main, new QingSongYiXiaFragment());
                        break;
                    // 在线音乐
                    case 5:
                        transaction.replace(R.id.relativelayout_main, new ZaiXianYinYueFragment());
                        break;
                    // 美图大全
                    case 6:
                        transaction.replace(R.id.relativelayout_main, new MeiTuDaQuanFragment());
                        break;
                    // 无聊点我
                    case 7:
                        transaction.replace(R.id.relativelayout_main, new TuLingJiQiRenFragment());
                        break;
                    // 生活常用
                    case 8:
                        transaction.replace(R.id.relativelayout_main, new ShengHuoChangYongFragment());
                        break;
                }
//                String text = listview_slidemenu.getAdapter().getItem(position).toString();
//                toolbar.setSubtitle(text);
                transaction.commit();
                drawerlayout_main.closeDrawer(slide_part);
            }
        });
    }

//    @Override
//    public boolean onPrepareOptionsMenu(Menu menu) {
//        // 判断Toolbar中添加的item是否可见
//        boolean isOpen = drawerlayout_main.isDrawerVisible(slide_part);
//        menu.findItem(R.id.toolbar_more).setVisible(!isOpen);
//        return super.onPrepareOptionsMenu(menu);
//    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //官方建议用if(drawerToggle.onOptionsItemSelected(item))的方法获取主按键的事件
        if (drawerToggle.onOptionsItemSelected(item)) {
            invalidateOptionsMenu();
        }
        switch (item.getItemId()) {
            case R.id.toolbar_more:
                // Snackbar.make(linearlayout_main, "你瞅啥", Snackbar.LENGTH_SHORT).show();
                Intent intent = new Intent(MainActivity.this, SetupActivity.class);
                startActivity(intent);
                break;
        }
        return true;
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    Snackbar.make(relativelayout_main, "服务器君离家出走了~", Snackbar.LENGTH_SHORT).show();
                    break;
                case 1:
                    listViewAdapter = new ListViewAdapter(MainActivity.this, lists);
                    listview_slidemenu.setAdapter(listViewAdapter);
                    break;
                case 2:
//                    for (int i = 0; i < newsClassEntity.getShowapi_res_body().getChannelList().size(); i++) {
//                        titlelists.add(newsClassEntity.getShowapi_res_body().getChannelList().get(i).getName());
//                    }
//                    fragmentAdapter = new FragmentAdapter(getSupportFragmentManager(), titlelists, fragmentlists);
//                    viewpager_main.setAdapter(fragmentAdapter);
//                    tablayout_main.setupWithViewPager(viewpager_main);
                    break;
            }
        }
    };

    // 重写onEventMainThread方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DBChangeEvent event) {
//        baseFragmentAdapter.notifyDataSetChanged();
        db = dbhelper.getWritableDatabase();
        dbmanager = new MyDBManager(dbhelper, db);
        tablists = dbmanager.querydata();
        for (int i = 0; i < tablists.size(); i++) {
            String channelName = tablists.get(i);
            BaseFragment baseFragment = BaseFragment.newInstance(channelName);
            defaultfragmentlists.add(baseFragment);
        }
        baseFragmentAdapter = new BaseFragmentAdapter(getSupportFragmentManager(), tablists, defaultfragmentlists);
        baseFragmentAdapter.notifyDataSetChanged();
        viewpager_main.setAdapter(baseFragmentAdapter);
        // 设置标题TabLayout
        tablayout_main.setupWithViewPager(viewpager_main);
        viewpager_main.setCurrentItem(tablists.size());
    }

    // 反注册EventBus
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(MainActivity.this);
    }
}
